//
//  NSSting+NYExtension.m
//  BS
//
//  Created by neal on 15/8/19.
//  Copyright (c) 2015年 Neal. All rights reserved.
//

#import "NSString+NYExtension.h"

@implementation NSString (NYExtension)
- (NSInteger)fileSize
{
    NSFileManager *filemanager = [NSFileManager defaultManager];

    BOOL isDirectory = NO;
    
    BOOL exist = [filemanager fileExistsAtPath:self isDirectory:&isDirectory];
    
    if (exist == NO) {
        return 0;
    }
    //文件夹
    if (isDirectory) {
        NSDirectoryEnumerator *enumerator = [filemanager enumeratorAtPath:self];
        
        NSInteger size = 0 ;
        
        for (NSString *subpath in enumerator) {
            NSString *filepath = [self stringByAppendingPathComponent:subpath];
            
            NSDictionary *attrs = [filemanager attributesOfItemAtPath:filepath error:nil];
            
            if ([attrs[NSFileType]isEqualToString:NSFileTypeDirectory]) {
                continue;
            }
            size += [attrs[NSFileSize] integerValue];
        }
        return size;

    }
    //文件
    return [[filemanager attributesOfItemAtPath:self error:nil][NSFileSize] integerValue];
}

- (NSString *)fileSizeString
{
    NSInteger fileSize = self.fileSize;
    CGFloat unit = 1000;
    if (fileSize>= unit * unit * unit)
    {
        return [NSString stringWithFormat:@"%.1fGB",fileSize/(unit * unit * unit)];
    }
    else if (fileSize>= unit * unit){
        return [NSString stringWithFormat:@"%.1fMB",fileSize/(unit * unit)];
    }
    else if (fileSize>= unit)
    {
        return [NSString stringWithFormat:@"%.1fKB",fileSize/(unit)];
    }
    else{
        return [NSString stringWithFormat:@"%zdB",fileSize];
    }
}
@end
